<template>
  <div class="backend-generator">

    <!-- 框架选择卡片 -->
    <el-card class="framework-selection" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Setting /></el-icon>
          <span>选择后端框架</span>
        </div>
      </template>

      <div class="framework-grid">
        <div
          v-for="framework in frameworks"
          :key="framework.id"
          class="framework-card"
          :class="{ 
            active: selectedFramework?.id === framework.id,
            disabled: framework.id !== 'spring-boot'
          }"
          @click="selectFramework(framework)"
        >
          <div class="framework-header">
            <div class="framework-language">{{ framework.language }}</div>
            <div class="framework-version">v{{ framework.version }}</div>
          </div>
          <div class="framework-icon">
            <div class="icon-wrapper">
              <el-icon size="32">
                <component :is="getFrameworkIcon(framework.id)" />
              </el-icon>
            </div>
            <div class="framework-badge" v-if="framework.id === 'spring-boot'">
              <span>推荐</span>
            </div>
            <div class="framework-badge disabled-badge" v-else>
              <span>暂未开发</span>
            </div>
          </div>
          <h3 class="framework-name">{{ framework.name }}</h3>
          <p class="framework-description">{{ framework.description }}</p>
          
          <div class="framework-features">
            <el-tag
              v-for="feature in framework.features.slice(0, 3)"
              :key="feature"
              size="small"
              type="info"
              effect="plain"
            >
              {{ feature }}
            </el-tag>
            <span v-if="framework.features.length > 3" class="more-features">
              +{{ framework.features.length - 3 }} 更多
            </span>
          </div>

          <div class="framework-actions">
            <el-button
              v-if="selectedFramework?.id === framework.id"
              type="primary"
              size="small"
              @click.stop="showEnhancedConfigDialog"
            >
              <el-icon><Tools /></el-icon>
              高级配置
            </el-button>
            <el-button
              v-else
              size="small"
              @click.stop="selectFramework(framework)"
            >
              选择框架
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 增强版配置对话框 -->
    <el-dialog
      v-model="enhancedConfigVisible"
      :title="`${selectedFramework?.name || ''} 项目配置`"
      width="90%"
      :close-on-click-modal="false"
      class="enhanced-config-dialog"
      top="5vh"
    >
      <!-- 步骤指示器 -->
      <div class="steps-container">
        <el-steps :active="currentStep" align-center>
          <el-step title="基本信息" icon="InfoFilled" />
          <el-step title="数据库配置" icon="Coin" />
          <el-step title="技术栈选择" icon="Setting" />
          <el-step title="功能特性" icon="Tools" />
          <el-step title="部署配置" icon="Upload" />
        </el-steps>
      </div>

      <!-- 配置内容 -->
      <div class="config-content">
        <!-- 步骤1: 基本信息 -->
        <div v-show="currentStep === 0" class="step-content">
          <h3 class="step-title">📋 项目基本信息</h3>
          <el-form :model="enhancedConfig" label-width="120px" class="config-form">
            <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="项目名称" required>
                  <el-input 
                    v-model="enhancedConfig.projectName" 
                    placeholder="my-awesome-api"
                    prefix-icon="Folder"
                  />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本号">
                  <el-input 
                    v-model="enhancedConfig.version" 
                    placeholder="1.0.0"
                    prefix-icon="PriceTag"
                  />
            </el-form-item>
          </el-col>
        </el-row>
        
            <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="包名" required>
                  <el-input 
                    v-model="enhancedConfig.packageName" 
                    placeholder="com.example.api"
                    prefix-icon="Box"
                  />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作者">
                  <el-input 
                    v-model="enhancedConfig.author" 
                    placeholder="开发者姓名"
                    prefix-icon="User"
                  />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="项目描述">
          <el-input
                v-model="enhancedConfig.description"
            type="textarea"
            :rows="3"
                placeholder="描述您的项目功能和特点..."
          />
        </el-form-item>
          </el-form>
        </div>

        <!-- 步骤2: 数据库配置 -->
        <div v-show="currentStep === 1" class="step-content">
          <h3 class="step-title">🗄️ 数据库配置</h3>
          
          <!-- 数据库类型选择 -->
          <div class="database-selection">
            <h4>选择数据库类型</h4>
            <div class="database-grid">
              <div
                v-for="db in databaseOptions"
                :key="db.type"
                class="database-card"
                :class="{ active: enhancedConfig.database.type === db.type }"
                @click="selectDatabase(db.type as 'mysql' | 'postgresql' | 'mongodb')"
              >
                <div class="database-icon">
                  <el-icon size="24">{{ db.icon }}</el-icon>
                </div>
                <h5>{{ db.name }}</h5>
                <p>{{ db.description }}</p>
                <div class="database-features">
                  <el-tag 
                    v-for="feature in db.features.slice(0, 2)" 
                    :key="feature"
                    size="small"
                    type="info"
                  >
                    {{ feature }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>

          <!-- 数据库连接配置 -->
          <el-form :model="enhancedConfig.database" label-width="120px" class="config-form">
            <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="主机地址">
                  <el-input v-model="enhancedConfig.database.host" placeholder="localhost" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="端口">
              <el-input-number
                    v-model="enhancedConfig.database.port"
                :min="1"
                :max="65535"
                    style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
                <el-form-item label="数据库名">
                  <el-input v-model="enhancedConfig.database.database" placeholder="api_db" />
            </el-form-item>
          </el-col>
            </el-row>

            <el-row :gutter="24">
              <el-col :span="12">
            <el-form-item label="用户名">
                  <el-input v-model="enhancedConfig.database.username" placeholder="root" />
            </el-form-item>
          </el-col>
              <el-col :span="12">
            <el-form-item label="密码">
              <el-input 
                    v-model="enhancedConfig.database.password" 
                type="password" 
                placeholder="数据库密码"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>

            <el-form-item>
              <el-button type="primary" @click="testDatabaseConnection" :loading="connectionStatus === 'testing'">
                <el-icon><Link /></el-icon>
                测试连接
              </el-button>
              <el-tag 
                v-if="connectionStatus === 'success'" 
                type="success" 
                style="margin-left: 8px;"
              >
                连接成功
              </el-tag>
              <el-tag 
                v-if="connectionStatus === 'failed'" 
                type="danger" 
                style="margin-left: 8px;"
              >
                连接失败
              </el-tag>
              </el-form-item>
          </el-form>
        </div>

        <!-- 步骤3: 技术栈选择 -->
        <div v-show="currentStep === 2" class="step-content">
          <h3 class="step-title">🛠️ 技术栈配置</h3>
          
          <!-- 对象存储 -->
          <div class="tech-section">
            <h4>📦 对象存储</h4>
            <div class="tech-grid">
              <div
                v-for="storage in storageOptions"
                :key="storage.type"
                class="tech-card"
                :class="{ active: enhancedConfig.objectStorage?.type === storage.type }"
                @click="selectStorage(storage.type as 'minio' | 's3' | 'oss')"
              >
                <div class="tech-icon">{{ storage.icon }}</div>
                <h5>{{ storage.name }}</h5>
                <p>{{ storage.description }}</p>
              </div>
            </div>

            <!-- 存储配置 -->
            <div v-if="enhancedConfig.objectStorage" class="tech-config">
              <el-form :model="enhancedConfig.objectStorage.config" label-width="120px">
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="服务端点">
                      <el-input 
                        v-model="enhancedConfig.objectStorage.config.endpoint" 
                        placeholder="http://localhost:9000"
                />
              </el-form-item>
            </el-col>
                  <el-col :span="12">
                    <el-form-item label="存储桶名称">
                <el-input 
                        v-model="enhancedConfig.objectStorage.config.bucketName" 
                        placeholder="my-bucket"
                />
              </el-form-item>
            </el-col>
          </el-row>
                <el-row :gutter="24">
            <el-col :span="12">
                    <el-form-item label="访问密钥">
                      <el-input 
                        v-model="enhancedConfig.objectStorage.config.accessKey" 
                        placeholder="Access Key"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
                    <el-form-item label="秘密密钥">
                      <el-input 
                        v-model="enhancedConfig.objectStorage.config.secretKey" 
                        type="password"
                        placeholder="Secret Key"
                        show-password
                />
              </el-form-item>
            </el-col>
          </el-row>
              </el-form>
            </div>
          </div>

          <!-- 搜索引擎 -->
          <div class="tech-section">
            <h4>🔍 搜索引擎</h4>
            <div class="tech-grid">
              <div
                v-for="search in searchOptions"
                :key="search.type"
                class="tech-card"
                :class="{ active: enhancedConfig.searchEngine?.type === search.type }"
                @click="selectSearch(search.type as 'elasticsearch' | 'solr')"
              >
                <div class="tech-icon">{{ search.icon }}</div>
                <h5>{{ search.name }}</h5>
                <p>{{ search.description }}</p>
              </div>
        </div>

            <!-- 搜索引擎配置 -->
            <div v-if="enhancedConfig.searchEngine" class="tech-config">
              <el-form :model="enhancedConfig.searchEngine.config" label-width="120px">
                <el-row :gutter="24">
          <el-col :span="12">
                    <el-form-item label="主机地址">
                      <el-input 
                        v-model="enhancedConfig.searchEngine.config.hosts" 
                        placeholder="localhost:9200"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
                    <el-form-item label="索引前缀">
                      <el-input 
                        v-model="enhancedConfig.searchEngine.config.indexPrefix" 
                        placeholder="api"
              />
            </el-form-item>
          </el-col>
        </el-row>
                <el-row :gutter="24">
          <el-col :span="12">
                    <el-form-item label="用户名">
                      <el-input 
                        v-model="enhancedConfig.searchEngine.config.username" 
                        placeholder="elastic"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
                    <el-form-item label="密码">
                      <el-input 
                        v-model="enhancedConfig.searchEngine.config.password" 
                        type="password"
                        placeholder="搜索引擎密码"
                        show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
              </el-form>
            </div>
          </div>

          <!-- 消息队列 -->
          <div class="tech-section">
            <h4>📨 消息队列</h4>
            <div class="tech-grid">
              <div
                v-for="mq in messageQueueOptions"
                :key="mq.type"
                class="tech-card"
                :class="{ active: enhancedConfig.messageQueue?.type === mq.type }"
                @click="selectMessageQueue(mq.type as 'rabbitmq' | 'kafka' | 'rocketmq')"
              >
                <div class="tech-icon">{{ mq.icon }}</div>
                <h5>{{ mq.name }}</h5>
                <p>{{ mq.description }}</p>
              </div>
            </div>

            <!-- 消息队列配置 -->
            <div v-if="enhancedConfig.messageQueue" class="tech-config">
              <el-form :model="enhancedConfig.messageQueue.config" label-width="120px">
                <el-row :gutter="24">
                  <el-col :span="8">
                    <el-form-item label="主机地址">
                <el-input 
                        v-model="enhancedConfig.messageQueue.config.host" 
                        placeholder="localhost"
                      />
              </el-form-item>
            </el-col>
                  <el-col :span="8">
                    <el-form-item label="端口">
                <el-input-number
                        v-model="enhancedConfig.messageQueue.config.port" 
                  :min="1"
                        :max="65535"
                        style="width: 100%"
                />
              </el-form-item>
            </el-col>
                  <el-col :span="8">
                    <el-form-item label="用户名">
                      <el-input 
                        v-model="enhancedConfig.messageQueue.config.username" 
                        placeholder="admin"
                />
              </el-form-item>
            </el-col>
          </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="密码">
                      <el-input 
                        v-model="enhancedConfig.messageQueue.config.password" 
                        type="password"
                        placeholder="消息队列密码"
                        show-password
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item v-if="enhancedConfig.messageQueue.type === 'rabbitmq'" label="虚拟主机">
                      <el-input 
                        v-model="enhancedConfig.messageQueue.config.virtualHost" 
                        placeholder="/"
                      />
                    </el-form-item>
                    <el-form-item v-if="enhancedConfig.messageQueue.type === 'kafka'" label="Group ID">
                      <el-input 
                        v-model="enhancedConfig.messageQueue.config.groupId" 
                        placeholder="api-group"
                      />
                    </el-form-item>
            </el-col>
          </el-row>
      </el-form>
            </div>
            </div>
          </div>

        <!-- 步骤4: 功能特性 -->
        <div v-show="currentStep === 3" class="step-content">
          <h3 class="step-title">⚡ 功能特性</h3>
          
          <div class="features-grid">
            <div class="feature-card">
              <div class="feature-header">
                <el-icon size="24" color="#409eff"><Document /></el-icon>
                <h4>API 文档</h4>
                    </div>
              <p>自动生成 Swagger/OpenAPI 文档</p>
              <el-switch 
                v-model="enhancedConfig.features.enableSwagger"
                :disabled="!isFeatureSupported('swagger')"
                active-text="启用"
                inactive-text="禁用"
              />
              <div class="feature-tags">
                <el-tag v-if="isFeatureRecommended('swagger')" size="small" type="success">推荐</el-tag>
                <el-tag v-if="!isFeatureSupported('swagger')" size="small" type="info">不支持</el-tag>
                    </div>
              </div>

            <div class="feature-card">
              <div class="feature-header">
                <el-icon size="24" color="#67c23a"><Lock /></el-icon>
                <h4>安全认证</h4>
              </div>
              <p>JWT/OAuth2 安全认证体系</p>
              <el-switch 
                v-model="enhancedConfig.features.enableSecurity"
                :disabled="!isFeatureSupported('security')"
                active-text="启用"
                inactive-text="禁用"
              />
              <div class="feature-tags">
                <el-tag v-if="isFeatureRecommended('security')" size="small" type="success">推荐</el-tag>
                <el-tag v-if="!isFeatureSupported('security')" size="small" type="info">不支持</el-tag>
              </div>
              </div>

            <div class="feature-card">
              <div class="feature-header">
                <el-icon size="24" color="#e6a23c"><Coin /></el-icon>
                <h4>缓存支持</h4>
              </div>
              <p>Redis 分布式缓存</p>
              <el-switch 
                v-model="enhancedConfig.features.enableCache"
                :disabled="!isFeatureSupported('cache')"
                active-text="启用"
                inactive-text="禁用"
                @change="onCacheToggle"
              />
              <div class="feature-tags">
                <el-tag v-if="isFeatureRecommended('cache')" size="small" type="success">推荐</el-tag>
                <el-tag v-if="!isFeatureSupported('cache')" size="small" type="info">不支持</el-tag>
              </div>
              </div>

            <div class="feature-card">
              <div class="feature-header">
                <el-icon size="24" color="#f56c6c"><Box /></el-icon>
                <h4>容器化</h4>
              </div>
              <p>容器化部署 (可选)</p>
              <el-switch 
                v-model="enhancedConfig.features.enableDocker"
                :disabled="!isFeatureSupported('docker')"
                active-text="启用"
                inactive-text="禁用"
              />
              <div class="feature-tags">
                <el-tag v-if="isFeatureRecommended('docker')" size="small" type="success">推荐</el-tag>
                <el-tag v-if="!isFeatureSupported('docker')" size="small" type="info">不支持</el-tag>
              </div>
              </div>

            <div class="feature-card">
              <div class="feature-header">
                <el-icon size="24" color="#909399"><Monitor /></el-icon>
                <h4>监控告警</h4>
              </div>
              <p>Prometheus + Grafana 监控</p>
              <el-switch 
                v-model="enhancedConfig.features.enableMonitoring"
                active-text="启用"
                inactive-text="禁用"
              />
              <div class="feature-tags">
                <el-tag size="small" type="success">推荐</el-tag>
            </div>
          </div>
            </div>
            
          <!-- JWT 配置 -->
          <div v-if="enhancedConfig.features.enableSecurity" class="jwt-config">
            <h4>🔐 JWT 安全配置</h4>
            <el-form :model="enhancedConfig.jwt" label-width="120px">
              <el-row :gutter="24">
                <el-col :span="16">
                  <el-form-item label="JWT 密钥">
                <el-input 
                      v-model="enhancedConfig.jwt.secret" 
                      placeholder="JWT 签名密钥"
                      type="password"
                      show-password
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="">
                    <el-button @click="generateJwtSecret" style="margin-top: 32px;">
                      <el-icon><Refresh /></el-icon>
                      生成密钥
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="过期时间(小时)">
                    <el-input-number 
                      v-model="enhancedConfig.jwt.expiration" 
                      :min="1"
                      :max="168"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="刷新过期(天)">
                    <el-input-number 
                      v-model="enhancedConfig.jwt.refreshExpiration" 
                      :min="1"
                      :max="30"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
              </div>

          <!-- Redis 配置 -->
          <div v-if="enhancedConfig.features.enableCache" class="redis-config">
            <h4>🗄️ Redis 缓存配置</h4>
            <el-form :model="enhancedConfig.redis" label-width="120px">
              <el-row :gutter="24">
                <el-col :span="8">
                  <el-form-item label="Redis 主机">
                    <el-input v-model="enhancedConfig.redis.host" placeholder="localhost" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="Redis 端口">
                    <el-input-number 
                      v-model="enhancedConfig.redis.port" 
                      :min="1"
                      :max="65535"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="数据库">
                    <el-input-number 
                      v-model="enhancedConfig.redis.database" 
                      :min="0"
                      :max="15"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="Redis 密码">
                <el-input 
                      v-model="enhancedConfig.redis.password" 
                  type="password" 
                      placeholder="Redis 密码(可选)"
                  show-password
                />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="连接超时(ms)">
                    <el-input-number 
                      v-model="enhancedConfig.redis.timeout" 
                      :min="1000"
                      :max="30000"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            </div>
          </div>

        <!-- 步骤5: 部署配置 -->
        <div v-show="currentStep === 4" class="step-content">
          <h3 class="step-title">🚀 部署配置</h3>
          
          <el-form :model="enhancedConfig.deployment" label-width="120px" class="config-form">
            <div class="deployment-section">
              <h4>🌐 端口配置</h4>
              <el-row :gutter="24">
                <el-col :span="8">
                  <el-form-item label="开发端口">
                  <el-input-number
                      v-model="enhancedConfig.deployment.devPort" 
                      :min="1000"
                      :max="65535"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="生产端口">
                    <el-input-number 
                      v-model="enhancedConfig.deployment.prodPort" 
                      :min="1000"
                      :max="65535"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="容器端口">
                    <el-input-number 
                      v-model="enhancedConfig.deployment.containerPort" 
                      :min="1000"
                      :max="65535"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
                </div>

            <div class="deployment-section">
              <h4 v-if="selectedFramework?.language === 'Java'">💾 JVM 配置</h4>
              <h4 v-else-if="selectedFramework?.language === 'JavaScript'">🟢 Node.js 配置</h4>
              <h4 v-else-if="selectedFramework?.language === 'Python'">🐍 Python 配置</h4>
              <h4 v-else>⚙️ 运行时配置</h4>
              
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item v-if="selectedFramework?.language === 'Java'" label="内存配置">
                    <el-select v-model="enhancedConfig.deployment.jvmMemory" style="width: 100%">
                      <el-option label="512MB (开发)" value="512m" />
                      <el-option label="1GB (测试)" value="1g" />
                      <el-option label="2GB (生产)" value="2g" />
                      <el-option label="4GB (高负载)" value="4g" />
                    </el-select>
                  </el-form-item>
                  <el-form-item v-else-if="selectedFramework?.language === 'JavaScript'" label="Node.js 版本">
                    <el-select v-model="enhancedConfig.deployment.nodeVersion" style="width: 100%">
                      <el-option label="Node.js 20 LTS" value="20" />
                      <el-option label="Node.js 18 LTS" value="18" />
                      <el-option label="Node.js 16 LTS" value="16" />
                    </el-select>
                  </el-form-item>
                  <el-form-item v-else-if="selectedFramework?.language === 'Python'" label="Python 版本">
                    <el-select v-model="enhancedConfig.deployment.pythonVersion" style="width: 100%">
                      <el-option label="Python 3.11" value="3.11" />
                      <el-option label="Python 3.10" value="3.10" />
                      <el-option label="Python 3.9" value="3.9" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col v-if="enhancedConfig.features.enableDocker" :span="12">
                  <el-form-item label="基础镜像">
                    <el-select v-model="enhancedConfig.deployment.baseImage" style="width: 100%">
                      <template v-if="selectedFramework?.language === 'Java'">
                        <el-option label="OpenJDK 17 Alpine" value="openjdk:17-jdk-alpine" />
                        <el-option label="OpenJDK 11 Alpine" value="openjdk:11-jdk-alpine" />
                        <el-option label="OpenJDK 8 Alpine" value="openjdk:8-jdk-alpine" />
                      </template>
                      <template v-else-if="selectedFramework?.language === 'JavaScript'">
                        <el-option label="Node.js 20 Alpine" value="node:20-alpine" />
                        <el-option label="Node.js 18 Alpine" value="node:18-alpine" />
                        <el-option label="Node.js 16 Alpine" value="node:16-alpine" />
                      </template>
                      <template v-else-if="selectedFramework?.language === 'Python'">
                        <el-option label="Python 3.11 Alpine" value="python:3.11-alpine" />
                        <el-option label="Python 3.10 Alpine" value="python:3.10-alpine" />
                        <el-option label="Python 3.9 Alpine" value="python:3.9-alpine" />
                      </template>
                      <template v-else>
                        <el-option label="Ubuntu 22.04" value="ubuntu:22.04" />
                        <el-option label="Alpine Linux" value="alpine:latest" />
                      </template>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col v-if="!enhancedConfig.features.enableDocker" :span="12">
                  <el-form-item label="部署方式">
                    <el-select v-model="enhancedConfig.deployment.deploymentType" style="width: 100%">
                      <template v-for="option in getDeploymentOptions()" :key="option.value">
                        <el-option :label="option.label" :value="option.value">
                          <div style="display: flex; align-items: center; justify-content: space-between;">
                            <span>{{ option.icon }} {{ option.label }}</span>
                            <el-tag v-if="option.recommended" size="small" type="success">推荐</el-tag>
                </div>
                        </el-option>
                      </template>
                    </el-select>
                    <div style="margin-top: 8px; font-size: 12px; color: #909399;">
                      {{ getDeploymentDescription() }}
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
                </div>
          </el-form>

          <!-- 配置预览 -->
          <div class="config-preview">
            <h4>📋 配置预览</h4>
            <el-card shadow="never" class="preview-card">
              <div class="preview-content">
                <div class="preview-item">
                  <strong>项目:</strong> {{ enhancedConfig.projectName }} ({{ enhancedConfig.version }})
                </div>
                <div class="preview-item">
                  <strong>框架:</strong> {{ selectedFramework?.name }}
              </div>
                <div class="preview-item">
                  <strong>数据库:</strong> {{ enhancedConfig.database.type }} @ {{ enhancedConfig.database.host }}:{{ enhancedConfig.database.port }}
            </div>
                <div class="preview-item">
                  <strong>部署方式:</strong> 
                  <el-tag v-if="enhancedConfig.features.enableDocker" type="primary" size="small">
                    Docker ({{ enhancedConfig.deployment.baseImage }})
                  </el-tag>
                  <el-tag v-else type="success" size="small">
                    {{ getDeploymentTypeLabel() }}
                  </el-tag>
          </div>
                <div v-if="enhancedConfig.objectStorage" class="preview-item">
                  <strong>对象存储:</strong> {{ enhancedConfig.objectStorage.type.toUpperCase() }}
            </div>
                <div v-if="enhancedConfig.searchEngine" class="preview-item">
                  <strong>搜索引擎:</strong> {{ enhancedConfig.searchEngine.type }}
              </div>
                <div v-if="enhancedConfig.messageQueue" class="preview-item">
                  <strong>消息队列:</strong> {{ enhancedConfig.messageQueue.type.toUpperCase() }}
            </div>
                <div class="preview-item">
                  <strong>功能特性:</strong>
                  <el-tag v-if="enhancedConfig.features.enableSwagger" size="small" type="success">API文档</el-tag>
                  <el-tag v-if="enhancedConfig.features.enableSecurity" size="small" type="warning">安全认证</el-tag>
                  <el-tag v-if="enhancedConfig.features.enableCache" size="small" type="info">缓存</el-tag>
                  <el-tag v-if="enhancedConfig.features.enableDocker" size="small" type="primary">Docker</el-tag>
                  <el-tag v-if="enhancedConfig.features.enableMonitoring" size="small">监控</el-tag>
          </div>
          </div>
            </el-card>
          </div>
        </div>
      </div>

      <!-- 对话框底部 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="prevStep" :disabled="currentStep === 0">
            <el-icon><ArrowLeft /></el-icon>
            上一步
            </el-button>
            <el-button 
            v-if="currentStep < 4" 
            type="primary" 
            @click="nextStep"
          >
            下一步
            <el-icon><ArrowRight /></el-icon>
            </el-button>
            <el-button 
            v-if="currentStep === 4" 
            type="success" 
            @click="saveEnhancedConfig"
          >
            <el-icon><Check /></el-icon>
            保存配置
          </el-button>
          <el-button @click="enhancedConfigVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 项目配置摘要 -->
    <el-card v-if="selectedFramework" class="project-config" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Files /></el-icon>
          <span>项目配置摘要</span>
          <div class="header-actions">
            <el-button type="primary" @click="showEnhancedConfigDialog">
              <el-icon><Edit /></el-icon>
              编辑配置
            </el-button>
            <el-button type="success" @click="generateCode" :loading="generating">
              <el-icon><Download /></el-icon>
              生成代码
            </el-button>
          </div>
        </div>
      </template>

      <div class="config-summary">
        <div class="summary-grid">
          <div class="summary-item">
            <div class="summary-label">项目名称</div>
            <div class="summary-value">{{ enhancedConfig.projectName }}</div>
          </div>
          <div class="summary-item">
            <div class="summary-label">后端框架</div>
            <div class="summary-value">{{ selectedFramework.name }}</div>
          </div>
          <div class="summary-item">
            <div class="summary-label">数据库</div>
            <div class="summary-value">{{ enhancedConfig.database.type }} - {{ enhancedConfig.database.database }}</div>
          </div>
          <div class="summary-item">
            <div class="summary-label">包名</div>
            <div class="summary-value">{{ enhancedConfig.packageName }}</div>
          </div>
        </div>
        
        <div class="feature-summary">
          <div class="summary-label">启用功能</div>
          <div class="feature-tags">
            <el-tag v-if="enhancedConfig.features.enableSwagger" type="success" size="small">
              <el-icon><Document /></el-icon>
              API文档
            </el-tag>
            <el-tag v-if="enhancedConfig.features.enableSecurity" type="warning" size="small">
              <el-icon><Lock /></el-icon>
              安全认证
            </el-tag>
            <el-tag v-if="enhancedConfig.features.enableCache" type="info" size="small">
              <el-icon><Coin /></el-icon>
              缓存支持
            </el-tag>
            <el-tag v-if="enhancedConfig.features.enableDocker" type="primary" size="small">
              <el-icon><Box /></el-icon>
              Docker
            </el-tag>
            <el-tag v-if="enhancedConfig.features.enableMonitoring" size="small">
              <el-icon><Monitor /></el-icon>
              监控告警
            </el-tag>
            <el-tag v-if="enhancedConfig.objectStorage" type="success" size="small">
              📦 {{ enhancedConfig.objectStorage.type.toUpperCase() }}
            </el-tag>
            <el-tag v-if="enhancedConfig.searchEngine" type="warning" size="small">
              🔍 {{ enhancedConfig.searchEngine.type }}
            </el-tag>
            <el-tag v-if="enhancedConfig.messageQueue" type="info" size="small">
              📨 {{ enhancedConfig.messageQueue.type.toUpperCase() }}
            </el-tag>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 生成进度 -->
    <el-card v-if="generating" class="generation-progress" shadow="hover">
      <div class="progress-content">
        <el-progress :percentage="generationProgress" :status="generationStatus" :stroke-width="8" />
        <p class="progress-text">{{ generationText }}</p>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Setting, Tools, Files, Edit, Download, Check, InfoFilled, Refresh, 
  QuestionFilled, Connection, Lock, User, Coin, Link, Filter, 
  CaretBottom, CaretTop, ArrowLeft, ArrowRight, Document, Box, 
  Monitor, Upload, Folder, PriceTag, Coffee, Lightning, 
  Grid, Star, Service, DataBoard, TrendCharts, Platform
} from '@element-plus/icons-vue'
import { backendFrameworks, type BackendFramework, type CodeGenerationConfig } from '../templates/backend-frameworks'
import { CodeGeneratorService } from '../services/codeGenerator'
import { DatabaseService, type DatabaseConnection, type DatabaseTable } from '../services/databaseService'
import { databaseApi, codeGenerationApi, type DatabaseTableVO, type DatabaseType } from "@/common/apis"
import { FrontendCodeGenerator, type ProjectConfig } from '../services/frontendCodeGenerator'

// 增强配置类型
interface ObjectStorageConfig {
  endpoint?: string
  accessKey?: string
  secretKey?: string
  bucketName?: string
  region?: string
}

interface SearchEngineConfig {
  hosts?: string
  indexPrefix?: string
  username?: string
  password?: string
  url?: string
  collection?: string
}

interface MessageQueueConfig {
  host?: string
  port?: number
  username?: string
  password?: string
  virtualHost?: string
  bootstrapServers?: string
  groupId?: string
  nameServer?: string
  groupName?: string
}

interface DeploymentConfig {
  devPort: number
  prodPort: number
  containerPort: number
  jvmMemory: '512m' | '1g' | '2g' | '4g'
  nodeVersion?: string
  pythonVersion?: string
  baseImage: string
}

interface EnhancedCodeGenerationConfig extends CodeGenerationConfig {
  objectStorage?: {
    type: 'minio' | 's3' | 'oss'
    config: ObjectStorageConfig
  }
  searchEngine?: {
    type: 'elasticsearch' | 'solr'
    config: SearchEngineConfig
  }
  messageQueue?: {
    type: 'rabbitmq' | 'kafka' | 'rocketmq'
    config: MessageQueueConfig
  }
  features: CodeGenerationConfig['features'] & {
    enableMonitoring: boolean
  }
  deployment: DeploymentConfig & {
    deploymentType?: string
  }
}

// 响应式数据
const frameworks = ref<BackendFramework[]>([])
const selectedFramework = ref<BackendFramework | null>(null)
const generating = ref(false)
const generationProgress = ref(0)
const generationStatus = ref<'success' | 'exception' | ''>('')
const generationText = ref('')

// 前端代码生成器实例
const frontendGenerator = new FrontendCodeGenerator()

// 增强配置对话框
const enhancedConfigVisible = ref(false)
const currentStep = ref(0)
const connectionStatus = ref<'idle' | 'testing' | 'success' | 'failed'>('idle')

// 数据库选项
const databaseOptions = ref([
  {
  type: 'mysql',
    name: 'MySQL',
    description: '最流行的开源关系型数据库',
    icon: '🐬',
    features: ['ACID事务', '高性能', '易于使用']
  },
  {
    type: 'postgresql',
    name: 'PostgreSQL',
    description: '功能强大的开源对象关系型数据库',
    icon: '🐘',
    features: ['JSON支持', '扩展性强', '标准兼容']
  },
  {
    type: 'mongodb',
    name: 'MongoDB',
    description: '面向文档的NoSQL数据库',
    icon: '🍃',
    features: ['文档存储', '水平扩展', '灵活模式']
  }
])

// 存储选项
const storageOptions = ref([
  {
    type: 'minio',
    name: 'MinIO',
    description: '高性能对象存储服务',
    icon: '🗄️'
  },
  {
    type: 's3',
    name: 'Amazon S3',
    description: '亚马逊云对象存储',
    icon: '☁️'
  },
  {
    type: 'oss',
    name: '阿里云 OSS',
    description: '阿里云对象存储服务',
    icon: '🌐'
  }
])

// 搜索引擎选项
const searchOptions = ref([
  {
    type: 'elasticsearch',
    name: 'Elasticsearch',
    description: '分布式搜索和分析引擎',
    icon: '🔍'
  },
  {
    type: 'solr',
    name: 'Apache Solr',
    description: '企业级搜索平台',
    icon: '☀️'
  }
])

// 消息队列选项
const messageQueueOptions = ref([
  {
    type: 'rabbitmq',
    name: 'RabbitMQ',
    description: '可靠的消息代理',
    icon: '🐰'
  },
  {
    type: 'kafka',
    name: 'Apache Kafka',
    description: '分布式流处理平台',
    icon: '📨'
  },
  {
    type: 'rocketmq',
    name: 'RocketMQ',
    description: '阿里巴巴消息中间件',
    icon: '🚀'
  }
])

// 增强配置
const enhancedConfig = reactive<EnhancedCodeGenerationConfig>({
  framework: {} as BackendFramework,
  projectName: 'my-awesome-api',
  packageName: 'com.example.api',
  basePackage: 'com.example.api',
  author: '开发者',
  version: '1.0.0',
  description: '基于智能配置生成的企业级 API 项目',
  database: {
    type: 'mysql',
    host: 'localhost',
    port: 3306,
    database: 'ecommerce_order_system',
    username: 'root',
    password: 'root'
  },
  redis: {
    host: 'localhost',
    port: 6379,
    password: '',
    database: 0,
    timeout: 5000
  },
  jwt: {
    secret: '',
    expiration: 24,
    refreshExpiration: 7
  },
  features: {
    enableSwagger: true,
    enableSecurity: false,
    enableCache: false,
    enableDocker: false,
    enableMonitoring: false
  },
  deployment: {
    devPort: 8080,
    prodPort: 8080,
    containerPort: 8080,
    jvmMemory: '1g',
    nodeVersion: '20',
    pythonVersion: '3.11',
    baseImage: 'openjdk:17-jdk-alpine',
    deploymentType: 'jar'
  }
})

// 初始化
onMounted(() => {
  frameworks.value = backendFrameworks
})

// 获取框架图标
const getFrameworkIcon = (frameworkId: string) => {
  const iconMap: Record<string, any> = {
    'spring-boot': Coffee,
    'express': Lightning,
    'fastapi': Platform,
    'django': Grid,
    'laravel': Star,
    'nest': Service,
    'gin': DataBoard,
    'flask': TrendCharts
  }
  return iconMap[frameworkId] || Setting
}

// 获取部署选项
const getDeploymentOptions = () => {
  if (!selectedFramework.value) return []
  
  const language = selectedFramework.value.language
  
  const deploymentOptions: Record<string, Array<{value: string, label: string, icon: string, recommended?: boolean}>> = {
    'Java': [
      { value: 'jar', label: 'JAR包部署', icon: '☕', recommended: true },
      { value: 'war', label: 'WAR包部署', icon: '🏭' },
      { value: 'systemd', label: 'Systemd服务', icon: '⚙️' }
    ],
    'JavaScript': [
      { value: 'pm2', label: 'PM2进程管理', icon: '🚀', recommended: true },
      { value: 'node', label: 'Node.js直接运行', icon: '📦' },
      { value: 'systemd', label: 'Systemd服务', icon: '⚙️' },
      { value: 'forever', label: 'Forever守护进程', icon: '♾️' }
    ],
    'Python': [
      { value: 'gunicorn', label: 'Gunicorn WSGI', icon: '🦄', recommended: true },
      { value: 'uvicorn', label: 'Uvicorn ASGI', icon: '⚡' },
      { value: 'systemd', label: 'Systemd服务', icon: '⚙️' },
      { value: 'supervisor', label: 'Supervisor进程管理', icon: '👁️' }
    ]
  }
  
  return deploymentOptions[language] || []
}

// 获取部署描述
const getDeploymentDescription = () => {
  const deploymentType = enhancedConfig.deployment.deploymentType
  if (!deploymentType || !selectedFramework.value) return ''
  
  const descriptions: Record<string, string> = {
    // Java
    'jar': '生成可执行JAR包，使用java -jar命令运行',
    'war': '生成WAR包，部署到Tomcat等应用服务器',
    
    // Node.js
    'pm2': '使用PM2进程管理器，支持集群、监控、自动重启',
    'node': '直接使用node命令运行，适合开发环境',
    'forever': '使用Forever保持应用持续运行',
    
    // Python
    'gunicorn': '使用Gunicorn WSGI服务器，适合Django/Flask',
    'uvicorn': '使用Uvicorn ASGI服务器，适合FastAPI',
    'supervisor': '使用Supervisor进程管理，支持自动重启',
    
    // 通用
    'systemd': '注册为系统服务，开机自启动'
  }
  
  return descriptions[deploymentType] || '传统部署方式'
}

// 获取部署方式标签
const getDeploymentTypeLabel = () => {
  const deploymentType = enhancedConfig.deployment.deploymentType
  if (!deploymentType) return '未设置'
  
  const labels: Record<string, string> = {
    // Java
    'jar': 'JAR包部署',
    'war': 'WAR包部署',
    
    // Node.js
    'pm2': 'PM2进程管理',
    'node': 'Node.js直接运行',
    'forever': 'Forever守护进程',
    
    // Python
    'gunicorn': 'Gunicorn WSGI',
    'uvicorn': 'Uvicorn ASGI',
    'supervisor': 'Supervisor进程管理',
    
    // 通用
    'systemd': 'Systemd服务'
  }
  
  return labels[deploymentType] || deploymentType
}

// 选择框架
const selectFramework = (framework: BackendFramework) => {
  // 检查框架是否已开发完成
  if (framework.id !== 'spring-boot') {
    ElMessage.warning(`${framework.name} 框架暂未开发完成，敬请期待！`)
    return
  }
  
  selectedFramework.value = framework
  enhancedConfig.framework = framework
  
  // 根据框架动态调整配置项
  updateConfigForFramework(framework)
  
  ElMessage.success(`已选择 ${framework.name} 框架，部署方式: ${enhancedConfig.deployment.deploymentType}`)
}

// 根据框架更新配置
const updateConfigForFramework = (framework: BackendFramework) => {
  // 只支持Spring Boot框架
  if (framework.id === 'spring-boot') {
    // 重置所有功能为Spring Boot推荐配置
    enhancedConfig.features.enableSwagger = true
    enhancedConfig.features.enableSecurity = true
    enhancedConfig.features.enableCache = true
    enhancedConfig.features.enableDocker = false // 默认传统部署
    enhancedConfig.features.enableMonitoring = false
    
    // Spring Boot 专用配置
    enhancedConfig.database.type = 'mysql'
    enhancedConfig.database.host = 'localhost'
    enhancedConfig.database.port = 3306
    enhancedConfig.database.database = 'ecommerce_order_system'
    enhancedConfig.database.username = 'root'
    enhancedConfig.database.password = 'root'
    
    // 项目配置
    enhancedConfig.packageName = 'com.example.springbootapi'
    enhancedConfig.basePackage = 'com.example.springbootapi'
    enhancedConfig.projectName = 'spring-boot-api'
    enhancedConfig.description = '基于Spring Boot的企业级API项目'
    
    // 部署配置
    enhancedConfig.deployment.baseImage = 'openjdk:17-jdk-alpine'
    enhancedConfig.deployment.devPort = 8080
    enhancedConfig.deployment.prodPort = 8080
    enhancedConfig.deployment.containerPort = 8080
    enhancedConfig.deployment.jvmMemory = '1g'
    enhancedConfig.deployment.deploymentType = 'jar'
    
    // JWT配置
    enhancedConfig.jwt.expiration = 24
    enhancedConfig.jwt.refreshExpiration = 7
    if (!enhancedConfig.jwt.secret) {
      enhancedConfig.jwt.secret = generateRandomSecret()
    }
  }
}

// 生成随机密钥
const generateRandomSecret = () => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*'
  let secret = ''
  for (let i = 0; i < 32; i++) {
    secret += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return secret
}

// 显示增强配置对话框
const showEnhancedConfigDialog = () => {
  if (!selectedFramework.value) {
    ElMessage.warning('请先选择一个后端框架')
    return
  }
  enhancedConfigVisible.value = true
  currentStep.value = 0
}

// 步骤导航
const nextStep = () => {
  if (currentStep.value < 4) {
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 数据库选择
const selectDatabase = (type: 'mysql' | 'postgresql' | 'mongodb') => {
  enhancedConfig.database.type = type
  
  // 设置默认端口
  switch (type) {
    case 'mysql':
      enhancedConfig.database.port = 3306
      break
    case 'postgresql':
      enhancedConfig.database.port = 5432
      break
    case 'mongodb':
      enhancedConfig.database.port = 27017
      break
  }
}

// 存储选择
const selectStorage = (type: 'minio' | 's3' | 'oss') => {
  if (enhancedConfig.objectStorage?.type === type) {
    // 如果已选择相同类型，则取消选择
    enhancedConfig.objectStorage = undefined
  } else {
    // 选择新的存储类型
    enhancedConfig.objectStorage = {
      type,
      config: getDefaultStorageConfig(type)
    }
  }
}

// 搜索引擎选择
const selectSearch = (type: 'elasticsearch' | 'solr') => {
  if (enhancedConfig.searchEngine?.type === type) {
    // 如果已选择相同类型，则取消选择
    enhancedConfig.searchEngine = undefined
  } else {
    // 选择新的搜索引擎类型
    enhancedConfig.searchEngine = {
      type,
      config: getDefaultSearchConfig(type)
    }
  }
}

// 消息队列选择
const selectMessageQueue = (type: 'rabbitmq' | 'kafka' | 'rocketmq') => {
  if (enhancedConfig.messageQueue?.type === type) {
    // 如果已选择相同类型，则取消选择
    enhancedConfig.messageQueue = undefined
  } else {
    // 选择新的消息队列类型
    enhancedConfig.messageQueue = {
      type,
      config: getDefaultMQConfig(type)
    }
  }
}

// 获取默认存储配置
const getDefaultStorageConfig = (type: string): ObjectStorageConfig => {
  const configs: Record<string, ObjectStorageConfig> = {
    minio: {
      endpoint: 'http://localhost:9000',
      accessKey: 'minioadmin',
      secretKey: 'minioadmin',
      bucketName: 'api-bucket'
    },
    s3: {
      region: 'us-east-1',
      bucketName: 'my-api-bucket'
    },
    oss: {
      endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
      bucketName: 'my-api-bucket'
    }
  }
  return configs[type] || {}
}

// 获取默认搜索配置
const getDefaultSearchConfig = (type: string): SearchEngineConfig => {
  const configs: Record<string, SearchEngineConfig> = {
    elasticsearch: {
      hosts: 'localhost:9200',
      indexPrefix: 'api',
      username: 'elastic'
    },
    solr: {
      url: 'http://localhost:8983/solr',
      collection: 'api_collection'
    }
  }
  return configs[type] || {}
}

// 获取默认消息队列配置
const getDefaultMQConfig = (type: string): MessageQueueConfig => {
  const configs: Record<string, MessageQueueConfig> = {
    rabbitmq: {
      host: 'localhost',
      port: 5672,
      username: 'guest',
      password: 'guest',
      virtualHost: '/'
    },
    kafka: {
      bootstrapServers: 'localhost:9092',
      groupId: 'api-group'
    },
    rocketmq: {
      nameServer: 'localhost:9876',
      groupName: 'api_group'
    }
  }
  return configs[type] || {}
}

// 缓存开关切换处理
const onCacheToggle = (enabled: boolean) => {
  if (enabled) {
    ElMessage.info('已启用Redis缓存，请配置Redis连接信息')
  }
}

// 测试数据库连接
const testDatabaseConnection = async () => {
  connectionStatus.value = 'testing'
  
  try {
    // 调用后端数据库连接测试API
    const result = await databaseApi.testConnection({
      databaseType: enhancedConfig.database.type.toUpperCase() as DatabaseType,
      host: enhancedConfig.database.host,
      port: enhancedConfig.database.port,
      database: enhancedConfig.database.database,
      username: enhancedConfig.database.username,
      password: enhancedConfig.database.password,
      charset: 'utf8',
      timeout: 30,
      useSSL: false
    })
    
    if (result.data && result.data.success) {
      connectionStatus.value = 'success'
      ElMessage.success(`数据库连接成功！${result.data.databaseProductName} ${result.data.databaseProductVersion}`)
    } else {
      connectionStatus.value = 'failed'
      ElMessage.error(`数据库连接失败：${result.data?.message || '连接失败'}`)
    }
  } catch (error: any) {
    connectionStatus.value = 'failed'
    ElMessage.error(`数据库连接失败：${error.message || '未知错误'}`)
  }
}

// 生成JWT密钥
const generateJwtSecret = () => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*'
  let secret = ''
  for (let i = 0; i < 64; i++) {
    secret += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  enhancedConfig.jwt.secret = secret
  ElMessage.success('JWT密钥已生成')
}

// 检查功能是否被框架支持
const isFeatureSupported = (feature: string) => {
  if (!selectedFramework.value) return true
  
  const framework = selectedFramework.value
  const featureMap: Record<string, string[]> = {
    swagger: ['API文档', 'Swagger', 'OpenAPI', 'Knife4j'],
    security: ['安全', 'JWT', 'OAuth', 'Security', '认证'],
    cache: ['缓存', 'Redis', 'Cache'],
    docker: ['Docker', '容器', '容器化']
  }
  
  const keywords = featureMap[feature] || []
  return keywords.some(keyword => 
    framework.features.some(f => f.includes(keyword))
  )
}

// 检查功能是否被框架推荐
const isFeatureRecommended = (feature: string) => {
  if (!selectedFramework.value) return false
  
  const framework = selectedFramework.value
  
  if (framework.id === 'spring-boot') {
    return ['swagger', 'security', 'cache', 'docker'].includes(feature)
  } else if (framework.id === 'express') {
    return ['swagger', 'security', 'cache', 'docker'].includes(feature)
  } else if (framework.id === 'fastapi') {
    return ['swagger', 'security', 'cache', 'docker'].includes(feature)
  }
  
  return false
}

// 保存增强配置
const saveEnhancedConfig = () => {
  // 验证必填项
  if (!enhancedConfig.projectName.trim()) {
    ElMessage.error('请输入项目名称')
    return
  }
  if (!enhancedConfig.packageName.trim()) {
    ElMessage.error('请输入包名')
    return
  }
  if (!enhancedConfig.database.database.trim()) {
    ElMessage.error('请输入数据库名称')
    return
  }

  enhancedConfigVisible.value = false
  ElMessage.success('配置保存成功！')
}

// 生成代码
const generateCode = async () => {
  if (!selectedFramework.value) {
    ElMessage.warning('请先选择并配置后端框架')
    return
  }

  try {
    const result = await ElMessageBox.confirm(
      `确定要生成 ${selectedFramework.value.name} 项目代码吗？`,
      '确认生成',
      {
        confirmButtonText: '确定生成',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    if (result === 'confirm') {
      await startGeneration()
    }
  } catch {
    // 用户取消
  }
}

// 开始生成
const startGeneration = async () => {
  generating.value = true
  generationProgress.value = 0
  generationStatus.value = ''
  generationText.value = '正在初始化生成环境...'

  try {
    // 步骤1: 获取数据库表结构
    generationText.value = '正在获取数据库表结构...'
    generationProgress.value = 20
    
    const tablesResponse = await databaseApi.getTables({
      databaseType: enhancedConfig.database.type.toUpperCase() as DatabaseType,
      host: enhancedConfig.database.host,
      port: enhancedConfig.database.port,
      database: enhancedConfig.database.database,
      username: enhancedConfig.database.username,
      password: enhancedConfig.database.password,
      charset: 'utf8',
      timeout: 30,
      useSSL: false
    })
    
    if (!tablesResponse.data || !tablesResponse.data.length) {
      throw new Error('未找到数据库表，请检查数据库连接和权限')
    }

    // 步骤2: 获取表字段信息
    generationText.value = '正在获取表字段信息...'
    generationProgress.value = 40
    
    const tablesData = []
    for (const table of tablesResponse.data) {
      const fieldsResponse = await databaseApi.getTableDetail(table.tableName, {
        databaseType: enhancedConfig.database.type.toUpperCase() as DatabaseType,
        host: enhancedConfig.database.host,
        port: enhancedConfig.database.port,
        database: enhancedConfig.database.database,
        username: enhancedConfig.database.username,
        password: enhancedConfig.database.password,
        charset: 'utf8',
        timeout: 30,
        useSSL: false
      })
      
      // 确保字段数据的完整性和类型安全
      const processedFields = (fieldsResponse.data?.fields || []).map(field => ({
        ...field,
        fieldName: field.fieldName || '',
        fieldType: field.fieldType || 'VARCHAR',
        fieldComment: field.fieldComment || '',
        defaultValue: field.defaultValue || '',
        javaType: field.javaType || 'String',
        jdbcType: field.jdbcType || 'VARCHAR'
      }))

      tablesData.push({
        tableName: table.tableName || '',
        tableComment: table.tableComment || '',
        fields: processedFields
      })
    }

    // 步骤3: 构建项目配置
    generationText.value = '正在构建项目配置...'
    generationProgress.value = 60
    
    const projectConfig: ProjectConfig = {
      projectName: enhancedConfig.projectName,
      packageName: enhancedConfig.packageName,
      author: enhancedConfig.author,
      version: enhancedConfig.version,
      description: enhancedConfig.description,
      frameworkType: selectedFramework.value.id,
      
      // 数据库配置
      database: {
        type: String(enhancedConfig.database.type || 'MYSQL').toUpperCase(),
        host: enhancedConfig.database.host || 'localhost',
        port: enhancedConfig.database.port || 3306,
        database: enhancedConfig.database.database || '',
        username: enhancedConfig.database.username || '',
        password: enhancedConfig.database.password || ''
      },
      
      // Redis配置（可选）
      redis: enhancedConfig.features.enableCache ? {
        host: enhancedConfig.redis.host,
        port: enhancedConfig.redis.port,
        password: enhancedConfig.redis.password,
        database: enhancedConfig.redis.database,
        timeout: enhancedConfig.redis.timeout
      } : undefined,
      
      // JWT配置（可选）
      jwt: enhancedConfig.features.enableSecurity ? {
        secret: enhancedConfig.jwt.secret || 'apiGeneratorPlatformJwtSecretKey2025',
        expiration: enhancedConfig.jwt.expiration, // 小时
        refreshExpiration: enhancedConfig.jwt.refreshExpiration // 天
      } : undefined,
      
      // 功能开关 - 传递用户的完整配置
      features: {
        enableSecurity: enhancedConfig.features.enableSecurity,
        enableCache: enhancedConfig.features.enableCache,
        enableDocker: enhancedConfig.features.enableDocker,
        enableMonitoring: enhancedConfig.features.enableMonitoring,
        enableActuator: true // Spring Boot Actuator 默认启用
      }
    }

    // 步骤4: 使用前端生成器生成项目
    generationText.value = '正在初始化代码生成器...'
    generationProgress.value = 70
    
    // 模拟进度更新，让用户感受到生成过程
    await new Promise(resolve => setTimeout(resolve, 500))
    
    generationText.value = '正在生成实体类和DTO...'
    generationProgress.value = 80
    
    await new Promise(resolve => setTimeout(resolve, 300))
    
    generationText.value = '正在生成Service和Controller...'
    generationProgress.value = 90
    
    await frontendGenerator.generateProject(projectConfig, tablesData)

    generationText.value = '代码生成完成，正在打包下载...'
    generationProgress.value = 100
    
    await new Promise(resolve => setTimeout(resolve, 500))
    
    generationStatus.value = 'success'
    ElMessage.success('🎉 Spring Boot项目代码生成并下载成功！')
    
  } catch (error) {
    generationStatus.value = 'exception'
    ElMessage.error('代码生成失败，请检查配置后重试')
    console.error('Generation error:', error)
  } finally {
    setTimeout(() => {
    generating.value = false
    }, 2000)
  }
}
</script>

<style scoped lang="scss">
.backend-generator {
  padding: 24px;
}



.framework-selection, .project-config, .generation-progress {
    margin-bottom: 24px;
  border-radius: 12px;
  overflow: hidden;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .card-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    font-size: 16px;
    
    .header-icon {
      color: #409eff;
    }

    .header-actions {
      margin-left: auto;
      display: flex;
      gap: 8px;
    }
    }
  }

    .framework-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
      gap: 20px;
  margin-top: 16px;
    }

    .framework-card {
  padding: 24px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s ease;
      
      &.disabled {
        opacity: 0.6;
        cursor: not-allowed;
        background-color: #f5f7fa;
        
        &:hover {
          border-color: #e4e7ed;
          box-shadow: none;
        }
      }
  background: white;
  position: relative;

      &:hover {
        border-color: #409eff;
        transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
      }

      &.active {
        border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
      }

      .framework-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    margin-bottom: 16px;

    .framework-language, .framework-version {
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 12px;
      font-weight: 600;
      background: #f0f2f5;
      color: #606266;
    }
  }
  
  .framework-icon {
    text-align: center;
    margin-bottom: 16px;
    
    .icon-wrapper {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 48px;
      height: 48px;
      border-radius: 8px;
      background: #f0f9ff;
      color: #409eff;
    }
    
    .framework-badge {
      position: absolute;
      top: -4px;
      right: 50%;
      transform: translateX(50%);
      background: #67c23a;
      color: white;
      padding: 2px 6px;
      border-radius: 8px;
      font-size: 10px;
      font-weight: 600;
      
      &.disabled-badge {
        background: #909399;
        color: white;
      }
        }
      }

      .framework-name {
        font-size: 18px;
        font-weight: 600;
    margin-bottom: 8px;
    text-align: center;
        color: #303133;
      }

      .framework-description {
    font-size: 13px;
    color: #909399;
    margin-bottom: 16px;
    text-align: center;
        line-height: 1.5;
      }

      .framework-features {
        display: flex;
        flex-wrap: wrap;
        gap: 6px;
        margin-bottom: 16px;
    justify-content: center;
    
    .el-tag {
      font-size: 11px;
    }

        .more-features {
      font-size: 11px;
          color: #909399;
      padding: 2px 6px;
      background: #f5f7fa;
      border-radius: 4px;
        }
      }

      .framework-actions {
    text-align: center;
  }
}


// 增强配置对话框样式
.enhanced-config-dialog {
  .steps-container {
    margin-bottom: 32px;
    padding: 0 24px;
  }
  
  .config-content {
    max-height: 60vh;
    overflow-y: auto;
    padding: 0 24px;
  }
  
  .step-content {
    .step-title {
      font-size: 20px;
          font-weight: 600;
      color: #2c3e50;
      margin-bottom: 24px;
      text-align: center;
    }
  }
  
  .config-form {
    .el-form-item {
      margin-bottom: 20px;
    }
  }
}

// 数据库选择样式
.database-selection {
  margin-bottom: 32px;
  
  h4 {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
    color: #2c3e50;
  }
}

.database-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.database-card {
  padding: 20px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
      text-align: center;
  background: white;
  
  &:hover {
    border-color: #409eff;
    transform: translateY(-2px);
  }
  
  &.active {
    border-color: #409eff;
    background: #f0f9ff;
  }
  
  .database-icon {
    font-size: 24px;
    margin-bottom: 8px;
  }
  
  h5 {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 8px;
    color: #2c3e50;
  }
  
  p {
    font-size: 12px;
    color: #909399;
    margin-bottom: 12px;
    line-height: 1.4;
  }
  
  .database-features {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
    justify-content: center;
  }
}

// 技术栈选择样式
.tech-section {
  margin-bottom: 32px;
  
  h4 {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
    color: #2c3e50;
  }
}

.tech-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 16px;
  margin-bottom: 16px;
}

.tech-card {
  padding: 16px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
  background: white;
  
  &:hover {
    border-color: #409eff;
    transform: translateY(-2px);
  }
  
  &.active {
    border-color: #409eff;
    background: #f0f9ff;
  }
  
  .tech-icon {
    font-size: 24px;
    margin-bottom: 8px;
  }
  
  h5 {
    font-size: 14px;
        font-weight: 600;
    margin-bottom: 4px;
    color: #2c3e50;
  }
  
  p {
    font-size: 12px;
    color: #909399;
    line-height: 1.3;
  }
}

.tech-config {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

// 功能特性样式
.features-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
    margin-bottom: 32px;
}

.feature-card {
  padding: 24px;
  border: 2px solid #e1e8ed;
  border-radius: 12px;
  background: white;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: #409eff;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  }
  
  .feature-header {
      display: flex;
      align-items: center;
      gap: 8px;
    margin-bottom: 8px;
    
    h4 {
      font-size: 16px;
      font-weight: 600;
      color: #2c3e50;
      margin: 0;
    }
  }
  
  p {
    font-size: 14px;
    color: #909399;
    margin-bottom: 16px;
    line-height: 1.4;
  }
  
  .feature-tags {
    margin-top: 8px;
    display: flex;
    gap: 4px;
  }
}

.jwt-config, .redis-config {
  margin-top: 24px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  
  h4 {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
    color: #2c3e50;
  }
}

// 部署配置样式
.deployment-section {
  margin-bottom: 24px;
  
  h4 {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
    color: #2c3e50;
  }
}

.config-preview {
  margin-top: 24px;
  
  h4 {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
    color: #2c3e50;
  }
  
  .preview-card {
    background: #f8f9fa;
    
    .preview-content {
      .preview-item {
        margin-bottom: 8px;
        font-size: 14px;
        line-height: 1.5;
        
        strong {
          color: #2c3e50;
          margin-right: 8px;
        }
        
        .el-tag {
          margin-left: 4px;
        }
      }
    }
  }
}

// 项目配置摘要样式
.config-summary {
  .summary-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    margin-bottom: 24px;
  }
  
  .summary-item {
    .summary-label {
        font-size: 12px;
        color: #909399;
      margin-bottom: 4px;
    }
    
    .summary-value {
      font-size: 14px;
      font-weight: 600;
      color: #2c3e50;
    }
  }
  
  .feature-summary {
    .summary-label {
        font-size: 12px;
        color: #909399;
      margin-bottom: 8px;
    }
    
    .feature-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      
      .el-tag {
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }
  }
}

// 生成进度样式
.generation-progress {
  .progress-content {
    text-align: center;
    
    .progress-text {
      margin-top: 16px;
      font-size: 14px;
      color: #606266;
    }
  }
}

// 对话框底部样式
.dialog-footer {
    display: flex;
    justify-content: space-between;
  align-items: center;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

// 响应式设计
@media (max-width: 768px) {
  .backend-generator {
    padding: 16px;
  }
  
  .framework-grid {
    grid-template-columns: 1fr;
  }
  
  .database-grid, .tech-grid {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }
  
  .features-grid {
    grid-template-columns: 1fr;
  }
  
  .summary-grid {
    grid-template-columns: 1fr;
  }
}

// 深色主题兼容

:deep(.el-steps) {
  .el-step__title {
  font-weight: 600;
}
  
  .el-step.is-process .el-step__title {
    color: #409eff;
  }
}

:deep(.el-card) {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
</style>